"""Recursive file deletion functions. These functions provide an easy way to clean e.g. 
compiled python (.pyc) files."""
from khronos.utils import Logger, Prompt
from khronos.utils.files import find_files, suffix_filter
import os

_log = Logger()
_prompt = Prompt("Continue anyway?")

def clean_pyc(directory, recursive=False): 
    clean(directory, [suffix_filter(".pyc")], recursive)
    
def clean_backups(directory, recursive=False): 
    clean(directory, [suffix_filter(".BACKUP")], recursive)
    
def clean(directory, filters, recursive=True):
    _log.info("Beggining clean.")
    filematches = find_files(directory, filters, recursive)
    if len(filematches) == 0:
        _log.warn("No file matches found.")
        return
    for filepath in filematches:
        _log(filepath, indent=1)
    _log.warn("This program will permanently delete the selected files.")
    answer = _prompt()
    if answer not in ("y", "yes"):
        return
    for filepath in filematches:
        _log("Removing %s ..." % (filepath,), indent=1, newline=False)
        try:
            os.remove(filepath)
        except Exception, error:
            _log(" failed")
            _log.error("%s: %s" % (error.__class__.__name__, error))
        else:
            _log(" ok")
    _log.info("Clean finished.")
    
if __name__ == "__main__":
    from optparse import OptionParser
    import sys
    
    parser = OptionParser(description="Utility for cleaning files (e.g. .pyc).", 
                          usage="%prog [options] [suffixes]", version="%prog 0.0.1a")
    parser.add_option("-d", "--directory", dest="directory", type="string", default=".", 
                      help="specify the directory that should be cleaned")
    parser.add_option("-r", "--recursive", dest="recursive", action="store_true", default=False, 
                      help="make a recursive clean on the target directory")
    options, args = parser.parse_args(sys.argv)
    if len(args) < 2:
        print "Please specify at least one filename suffix."
        sys.exit(1)
        
    filters = [suffix_filter(suffix) for suffix in args[1:]]
    clean(options.directory, filters, options.recursive)
    sys.exit(0)
    
